<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="lib/layui/css/layui.css">
    <script src="lib/layui/layui.js"></script>
    <script src="lib/jquery-1.12.4.js"></script>
</head>
<body>

<script type="text/html" id="toolbarDemo">
    <form action="" class="layui-form">
        <div class="layui-inline">
            <label class="layui-form-label" style="width: 100px;">购货单号:</label>
            <div class="layui-input-block">
                <input type="text" autocomplete="off" class="layui-input" id="productName" value="">
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label" style="width: 100px;">单据日期：</label>
            <div class="layui-input-block">
                <input type="text" name="date" id="createDate" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<table class="layui-hide" id="test" lay-filter="test"></table>

<div class="layui-inline" style="margin-top: 20px;display: flex;justify-content: center;align-items: center">
    <button type="button" class="layui-btn layui-btn-normal" id="submit" onclick="addOrder()">生成购货订单</button>
    <button type="button" class="layui-btn layui-btn-primary" onclick="cancel()">取消</button>
</div>

</body>
<script>
    var idList = [];
    function tes(use) {
        var list = use;
        var count = list.length;
        for(let i=0;i<count;i++){
            idList.push(list[i].id);
        }
        //console.log(idList);
        layui.use(['table', 'laydate', 'jquery'], function () {
            var table = layui.table,
                laydate = layui.laydate, $ = layui.jquery;
            laydate.render({
                elem: '#createDate',
                type: 'date',
                format: 'yyyy-MM-dd',
                istoday: true,
                value: new Date
            });

            table.render({
                elem: '#test',
                url: 'htz/user/setTime',
                toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
                id: 'compelete',
                totalRow: true,
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": 0, //解析接口状态
                        "msg": "", //解析提示文本
                        "count": count, //解析数据长度
                        "data": list//解析数据列表
                    };
                },
                cols: [
                    [
                        {
                            field: 'goodsId',
                            title: '商品编号',
                            align: 'center',
                            totalRowText: '合计'
                        }, {
                        field: 'goodsName',
                        title: '商品名称',
                        align: 'center'
                    }, {
                        field: 'recomQuantity',
                        title: '补货数量',
                        align: 'center',
                        edit: 'text',
                        templet: function (d) {
                            var an = d.recomQuantity;
                            if (an.toString() == 0.00) {
                                return '0'
                            } else {
                                return Number(an).toFixed(2)
                            }
                        },
                        totalRow: true
                    }, {
                        field: 'purchasePrice',
                        title: '购入单价',
                        align: 'center',
                        templet: function (d) {
                            var an = d.purchasePrice;
                            if (an.toString() == 0.00) {
                                return '0'
                            } else {
                                return an.toString() + '.00'
                            }
                        }

                    }, {
                        field: 'productSum',
                        title: '商品总价',
                        align: 'center',
                        templet: function (d) {
                            let result = d.purchasePrice * d.recomQuantity;
                            return result.toFixed(2)
                        },
                        totalRow: true
                    }
                    ]
                ],
                done: function (res) {
                    let sum = $("[data-field='productSum']").find('.layui-table-cell');
                    let total = 0;
                    for (var i = 1; i < sum.length - 1; i++) {
                        total += Number(sum[i].innerText);
                    }
                    $(".layui-table-total").find("[data-field='productSum']").html(" <div class=\"layui-table-cell laytable-cell-1-0-4\" >" + Number(total).toFixed(2) + "</div>");
                }

            });

            table.on('tool(test)', function (obj) {
                // if (obj.event == 'del') {
                //     obj.del();
                //     //$('div.laytable-cell-checkbox').find('div.layui-form-checked').click();
                //     table.reload('compelete');
                //     laydate.render({
                //         elem: '#createDate',
                //         type: 'date',
                //         format: 'yyyy-MM-dd',
                //         istoday: true,
                //         value: new Date
                //     });
                //     format();
                //     var index = obj.tr.attr("data-index");
                //     //console.log(obj.tr.attr("data-index"));
                //     //var count = parent.find();
                //     //order(count);
                //     var check = parent.check(index);
                //     console.log(count);
                //     //parent.$('div.laytable-cell-checkbox').find("div").eq(index+1).click();
                // } else if (obj.event == 'history') {
                //     window.open('complement_history.html')
                // }

            });

            table.on('edit(test)', function (obj) {
                let data = obj.data;
                let quantity = data.recomQuantity;
                let goodsId = data.goodsId;
                let safetyStock = data.safetyStock;
                let field = obj.field; //得到字段
                let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;

                if (!(reg.test(quantity))) {
                    layer.open({
                        title: '系统提示'
                        , content: '请输入有效数量'
                        , success: function (layero, index) {
                            $(document).keydown(function (event) {
                                if (event.keyCode == 13 || event.keyCode == 108) {
                                    layer.closeAll();
                                }
                            });

                        }
                    });
                    obj.update({
                        recomQuantity: ""
                    })
                } else {
                    $.ajax({
                        url: 'xp/complete/verify',
                        data: {'goodsId': goodsId, 'quantity': quantity},
                        type: 'post',
                        dataType: 'json',
                        success: function (data) {
                            if (data.result == 'false') {
                                layer.open({
                                    title: '系统提示'
                                    , content: '已超过最大库存，请输入有效数量'
                                    , success: function (layero, index) {
                                        $(document).keydown(function (event) {
                                            if (event.keyCode == 13 || event.keyCode == 108) {
                                                layer.closeAll();
                                            }
                                        });

                                    }
                                });
                                obj.update({
                                    recomQuantity: ""
                                })
                            }

                        }

                    });
                    $("#submit").removeAttr("disabled");
                }
                table.reload('compelete');
                laydate.render({
                    elem: '#createDate',
                    type: 'date',
                    format: 'yyyy-MM-dd',
                    istoday: true,
                    value: new Date
                });
                format();
            });

            function format() {
                let date = new Date();
                let y = date.getFullYear().toString();
                let m = date.getMonth() + 1;
                let d = date.getDate();
                let hour = date.getHours().toString();
                let minutes = date.getMinutes().toString();
                let seconds = date.getSeconds().toString();
                let result = "Rep_"+y + m.toString() + d.toString() + hour + minutes + seconds;
                $("#productName").val(result);
            }
            format();
        });

    }

    function cancel() {
        $('#save').attr('disabled', 'disabled');
        parent.layer.closeAll();
    }

    function test() {
        let goodsId = $("[data-field='goodsId']").find(".layui-table-cell");
        let length = goodsId.length - 2;
        var temp = $("[data-field='recomQuantity']").find(".layui-table-cell");
        for (var i = 0; i < length; i++) {
            if(Number(temp.eq(i).html()) == 0){
                layer.msg("请确认输入数量大于0",{icon: 2});
                $("#submit").attr("disabled","true");
            }
        }
    }
    function addOrder() {
        test();
        let replenishment = {
            "replenishmentId": $("#productName").val(),
            "type": 1,
            "createdate": $("#createDate").val(),
            "sum": $("[data-field='productSum']:last").find('div').text()
        };
        //console.log(replenishment);
        let goodsId = $("[data-field='goodsId']").find(".layui-table-cell");
        //var quantityOfGoods = $("[data-field='quantityOfGoods']").find(".layui-table-cell");
        let length = goodsId.length - 2;
        let orderDetail = [];
        let id = [];
        for (var i = 0; i < length; i++) {
            let list = {};
            list.replenishmentId = $("#productName").val();
            list.goodsId = $("[data-field='goodsId']").find(".layui-table-cell").eq(i + 1).html();
            list.quantityOfGoods = $("[data-field='recomQuantity']").find(".layui-table-cell").eq(i + 1).html();
            orderDetail.push(list);
            id.push($("[data-field='goodsId']").find(".layui-table-cell").eq(i + 1).html());
        }
        var complementOrderUtil = {
            "replenishment": replenishment,
            "list" : orderDetail
        };
        //console.log(orderDetail);
        console.log(complementOrderUtil);
        $.ajax({
            url : 'xp/complete/add',
            data: JSON.stringify(complementOrderUtil),
            type: 'post',
            async: false,
            dataType: "json",
            traditional: true,
            contentType: "application/json;charset=UTF-8",
            success: function (data) {
                if(data.obj>=2){
                    layer.msg("补货单已生成",{icon: 6});
                    parent.updateStatus(idList);
                }

            },
            complete: function(){
                parent.layer.closeAll('iframe'); //关闭所有的iframe层
            },
            error: function () {
                layer.msg("后台出错，请稍后再试",{icon: 0,time: 2000})
            }
        })

    }

</script>
</html>